package com.itany.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.itany.constant.StatusConst;
import com.itany.pojo.User;
import com.itany.user.service.IUserService;
import com.itany.vo.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/userserver")
public class UserController {

    @Reference
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/addUser")
    @ResponseBody
    public ActionResult addUser(User user) {
        ActionResult ac = new ActionResult();
        userService.addUser(user);
        ac.setStatus(0);
        return ac;
    }

    @RequestMapping("/findUsers")
    public ModelAndView findUsers(@RequestParam(defaultValue = "1") Integer pageNo,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<User> pageInfo = userService.findUsers(pageNo, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);
        return new ModelAndView("userlist", map);
    }


    /**
     * 单点登录方法
     *
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ActionResult login(User user, HttpServletResponse response) {
        ActionResult ac = new ActionResult();
        User u = userService.login(user);
        if(u == null){
            ac.setMsg("用户名密码错误");
            ac.setStatus(StatusConst.FAIL_RESPONSE);
            return ac;
        }
        //生成token,用于作为redis的key
        String token = UUID.randomUUID().toString();
        //存入redis并设置过期时间
        redisTemplate.opsForValue().set("USER_TOKEN::" + token, JSON.toJSONString(u), 1800, TimeUnit.SECONDS);
        //将key存入cookie
        Cookie cookie = new Cookie("TT_TOKEN", token);
        cookie.setPath("/");
        response.addCookie(cookie);
//        return "redirect:http://localhost:9003/user/userserver/findUsers";
        return ac;
    }


}
